package com.zhuiyun.pm.client.login.controller;

import cn.hutool.core.util.RandomUtil;
import com.alipay.api.kms.aliyun.http.HttpRequest;
import com.wf.captcha.base.Captcha;

import com.zhuiyun.pm.client.login.Code.CodeUtils;
import com.zhuiyun.pm.client.login.entity.ClientUser;
import com.zhuiyun.pm.client.login.mapper.UserLoginDao;
import com.zhuiyun.pm.client.login.service.UserLoginService;
import com.zhuiyun.pm.config.CommonResult;
import com.zhuiyun.pm.utils.MailUtils;
import com.zhuiyun.pm.utils.Md5Util;
import com.zhuiyun.pm.utils.RedisUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.List;
import static com.zhuiyun.pm.client.login.utils.RandomValidateCodeUtil.RANDOMCODEKEY;

/**
 * @author syc
 * @date 2023/3/13 19:25
 */
@RestController
@CrossOrigin
@RequestMapping("/clientuser")
public class UserLoginController {
    public static final String RANDOMCODEKEY = "RANDOMVALIDATECODEKEY";//放到session中的key
    @Autowired
    UserLoginService clientUserService;
    @Autowired
    RedisUtil redisUtil;
    private RandomUtil IdUtil;
    @Autowired
    CodeUtils codeUtils;
    @Autowired
    UserLoginDao clientUserDao;
    @PostMapping("/backPassword")
    public  CommonResult backPassword(@RequestBody Map<String,String> map){
        final String code = map.get("code");
        final String userEmail = map.get("userEmail");
        final String a= (String) redisUtil.get(userEmail);
        System.out.println("a:"+a);
        System.out.println("code:"+code);
        if(!a.equals(null)&&a.equals(code)){
            ClientUser clientUser=new ClientUser();
            clientUser.setUserEmail(map.get("userEmail"));
            final List<ClientUser> select = clientUserDao.select(clientUser);
            if(!select.isEmpty()){
                final String userPassword = map.get("userPassword");
                final String md5DigestAsHex = Md5Util.getMd5DigestAsHex(userPassword);
                clientUser.setUserPassword(md5DigestAsHex);
                clientUser.setId( select.get(0).getId());
                redisUtil.del(select.get(0).getUserPhone());
                 int i = clientUserDao.updateByPrimaryKeySelective(clientUser);
                 if(i>0){
                     return CommonResult.ok("修改成功");
                 }else{
                     return CommonResult.ok("修改失败");
                 }
            }else {
                return CommonResult.error("邮箱不存在");
            }
        }else{
            return CommonResult.error("验证码不正确");
        }
    }

    @GetMapping("/sendQQMail")
    public CommonResult sendQQMail(String userEmail,String type){
        return clientUserService.sendMail(userEmail,type);
    }

    /**
     * 查询手机是否有该用户
     * 有的话存在redis中
     * @param clientUser
     * @return
     */
    @GetMapping("/queryByPhone")
    public CommonResult queryByPhone(ClientUser clientUser){
        return clientUserService.queryByPhone(clientUser);
    }

    /**
     * 用户登录方法
     * 密码登录
     * @param
     * @return
     */

    @PostMapping(value = "/userlogin", headers = "Accept=application/json")
    public CommonResult loginByPassWord(@RequestBody Map<String,String> map){

           String seccode=map.get("seccode");
        final String userPhone = map.get("userPhone");
        final String userPassword = map.get("userPassword");
        System.out.println("seccode::"+seccode);
        ClientUser clientUser=new ClientUser();
        clientUser.setUserPhone(userPhone);
        clientUser.setUserPassword(userPassword);
        String code= (String) redisUtil.get(seccode);
        if(!code.equals(null)&&code.equals("111")){
            return clientUserService.loginByPassWord(clientUser);
        }else {
            return CommonResult.error("验证码错误!请刷新");
        }

    }

    /**
    * @Author sgo
    * @Description  发送验证码
    * @Date 2023/3/14 18:46
    * @Return com.zhuiyun.pm.config.CommonResult
    * @param phone
    */
    @GetMapping("/sendloginByPhone")
    public CommonResult sendlgoinByPhone(String phone){
        return clientUserService.sendloginByPhone(phone);
    }

    /**
    * @Author sgo
    * @Description  验证码登录
    * @Date 2023/3/15 8:33
    * @Return com.zhuiyun.pm.config.CommonResult
    * @param map
    */
    @PostMapping("/loginByMail")
    public CommonResult lgoinByPhone(@RequestBody Map<String,String> map){
        final String userEmail = map.get("userEmail");
        final String code = map.get("code");
        return clientUserService.loginByPhone(userEmail,code);
    }
    /**
     * @Author 赵笛
     * @Description TODO 根据token获取当前登录的用户
     * @Date 2023/3/19 18:55
     * @Return com.zhuiyun.pm.config.CommonResult
     * @param token
     */
    @PostMapping("/getLoginUser")
    public CommonResult getLoginUser(@RequestBody String token){
        return clientUserService.getLoginUser(token);
    }


    @PostMapping(value = "/AppLogin", headers = "Accept=application/json")
    public CommonResult AppLogin(@RequestBody Map<String,String> map,HttpServletRequest request){



        final String userPhone = map.get("userPhone");
        final String userPassword = map.get("userPassword");
        ClientUser clientUser=new ClientUser();
        clientUser.setUserPhone(userPhone);
        clientUser.setUserPassword(userPassword);
        return clientUserService.loginByPassWord(clientUser);

    }
    /**
    * @Author sgo
    * @Description 注册  发送邮箱
    * @Date 2023/3/22 9:30
    * @Return com.zhuiyun.pm.config.CommonResult
    * @param map
    */
    @PostMapping("/register")
    public CommonResult register(@RequestBody Map<String,String> map){
        final String userPhone   = map.get("userPhone");
        final String code = map.get("code");
         String userEmail = map.get("userEmail");
        String userName=map.get("loginName");
        String userType=map.get("userType");
        String userPassword=map.get("userPassword");
        ClientUser clientUser=new ClientUser();
        clientUser.setUserPhone(userPhone);
        clientUser.setUserName(userName);
        clientUser.setUserEmail(userEmail);
        clientUser.setUserType(Integer.parseInt(userType));
        clientUser.setUserPassword(Md5Util.getMd5DigestAsHex(userPassword));
        clientUser.setDelFlag(0);
        clientUser.setUserStatus(0);
        clientUser.setCreateTime(new Date());
        return clientUserService.register(clientUser,code);
    }

    /**
     * 用户修改信息回显
     * @author 温
     * @date 2023/3/21 15:17
     * @parameter [id]
     * @return com.zhuiyun.pm.config.CommonResult
     */
    @GetMapping("/clientUserId")
    public CommonResult clientUserId(@RequestParam Integer id){// 前端路径拼接id后台用@PathVariable注解
        ClientUser clientUser = clientUserService.clientUserId(id);
        return CommonResult.ok(clientUser);
    }

    /**
     * 用户个人信息修改
     * @author 温
     * @date 2023/3/21 16:06
     * @parameter [file, clientUser]
     * @return com.zhuiyun.pm.config.CommonResult
     */
    @PostMapping("/clientUserUpdate")
    public CommonResult clientUserUpdate(MultipartFile file,ClientUser clientUser,HttpServletRequest request){
        final String token = request.getHeader("token");
        System.out.println("token:1"+token);

        System.out.println("clientUser::::"+clientUser);
        //数据进行修改的时候redis进行同步
        CommonResult i = clientUserService.clientUserUpdate(file, clientUser,token);
            //resdis数据进行删除，添加，(刷新)
//            return CommonResult.ok();

            return i;

    }
    /**
    * @Author sgo
    * @Description 删除token
    * @Date 2023/3/23 10:54
    * @Return com.zhuiyun.pm.config.CommonResult
    * @param
    */
    @GetMapping("/Deltoken")
    public CommonResult Deltoken(String token){
        System.out.println("token:"+token);
        redisUtil.del(token);
        return CommonResult.ok();
    }
    /**
    * @Author sgo
    * @Description 查询token
    * @Date 2023/3/27 8:33
    * @Return com.zhuiyun.pm.config.CommonResult
    * @param
    */
    @GetMapping("/queryByDelToken")
    public CommonResult queryByDelToken(String token){
//      String token= map.get("token");
//        System.out.println("token::"+token);
        try {
            final ClientUser clientUser = (ClientUser) redisUtil.get(token);
            return CommonResult.ok(clientUser);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.error("登陆过期");
        }
    }
    /**
    * @Author sgo
    * @Description 查询token
    * @Date 2023/3/30 8:37
    * @Return com.zhuiyun.pm.config.CommonResult
    * @param token
    */
    @GetMapping("/selectToken")
    public CommonResult selectToken(String token){
//        System.out.println("token::"+token);
        final boolean b = redisUtil.hasKey(token);
        if(b){
            return CommonResult.ok();
        }else{
            return CommonResult.error("1");
        }
    }
    /**
    * @Author sgo
    * @Description 修改密码
    * @Date 2023/3/30 14:09
    * @Return com.zhuiyun.pm.config.CommonResult
    * @param clientUser
    * @param request
    */
    @PostMapping("/revisePassWord")
    public CommonResult revisePassWord(@RequestBody ClientUser clientUser,HttpServletRequest request){
        final String s = request.getHeader("token");
        return clientUserService.revisePassWord(clientUser,s);
    }
    /**
    * @Author songyongcheng
    * 获取验证麻(返回的img属性可以直接放到图片得src中)登陆的时候需要携带code到(前端取data中的imgCode)
    * @Date 2023/3/30 14:10
    * @Return Map<String,Object>
    */

    @GetMapping("/code")
    @ApiOperation(value = "获取验证码", notes = "获取验证码")
    public Map<String,Object> getCode(){
//        调用验证码生成工具类
        Captcha captcha = codeUtils.switchCaptcha();
        String captchaValue = captcha.text();
        System.out.println("生成验证码值为::"+captchaValue);
        // 保存Redis中过期时间120秒
        redisUtil.set(captchaValue,"111",600);
        // 验证码信息
        Map<String,Object> imgResult = new HashMap<String,Object>(2){{
            put("imgCode",captcha.toBase64());
        }};
        return imgResult;
    }
    /**
    * @Author sgo
    * @Description 当前用户登录（客服聊天）
    * @Date 2023/4/1 9:33
    * @Return com.zhuiyun.pm.config.CommonResult
    * @param
    */
    @PostMapping("/NowLoginUser")
    public CommonResult NowLoginUser(@RequestBody String token) {
//        String token=map.get("token");
        final String[] split = token.split("=");
        System.out.println("token::" + split[0]);
        try {
            final ClientUser clientUser = (ClientUser) redisUtil.get(split[0]);
            return CommonResult.ok(clientUser);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.error("登陆超时");
        }
    }
    /**
     *用户模糊查
     * @author 温
     * @date 2023/4/4 16:32
     * @parameter [goodsName, startPrice]
     * @return com.zhuiyun.pm.config.CommonResult
     */
    @GetMapping("/userMo")
    public CommonResult userMo(ClientUser clientUser){
        List<ClientUser> clientUsers = clientUserService.userMo(clientUser);
        return CommonResult.ok(clientUsers);
    }


}
